package fuckNmap

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

func FuckNmap() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()
		// check
		if exist, f := checkNmap(c); c.Writer.Status() == http.StatusNotFound && exist {
			for _, item := range f {
				if item == nil {
					DefaultHandle(c)
				} else {
					item(c)
				}
			}
		}
	}
}

var NmapQueryPath = map[string]func(*gin.Context){}

func AddNmapQueryPath(query string, handle func(ctx *gin.Context)) {
	if query == "" || query == "/" {
		return
	}
	if query[0] != '/' {
		query = "/" + query
	}
	NmapQueryPath[query] = handle
}
func LoadNmpQueryPath(querys []string) {
	for _, item := range querys {
		AddNmapQueryPath(item, nil)
	}
}
func DefaultHandle(c *gin.Context) {
	c.Writer.WriteHeader(http.StatusOK)
	if _, err := c.Writer.WriteString("fuck your mother!!!!loser\nyou mother boom!!!\n"); err != nil {
		log.Printf("DefaultHandle WriteString err:%s\n", err.Error())
	}
}

/*
	RequestURI:/p NmapQuery:/phpmyadmin  x
	RequestURI:xxx/phpmyadmin/xxx?xxx NmapQuery:/phpmyadmin  √
	RequestURI:xxx/phpmyadmin?xxx NmapQuery:/phpmyadmin  √
*/
func checkNmap(c *gin.Context) (bool, []func(*gin.Context)) {
	f := make([]func(ctx *gin.Context), 0)
	exist := false
	for key, item := range NmapQueryPath {
		if strings.Contains(c.Request.RequestURI, key) {
			temp := strings.Split(c.Request.RequestURI, key)
			temp = temp[1:]
			for _, t := range temp {
				if t == "" || t[0] == '?' || t[0] == '/' {
					f = append(f, item)
					exist = true
				}
			}

		}
	}
	return exist, f
}
